﻿
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Diagnostics;

namespace System.Windows.Media.DirectShow.Filters
{
    internal class VideoRendererPin : BaseInputPin
    {

        // Preferrered type
        private AMMediaType[] _mediaTypes = new AMMediaType[] { new AMMediaType {
            MajorType = MediaMajorTypes.Video,
            SubType = MediaSubTypes.None,
        }};

        private DirectShowMediaStreamSource mediaStreamSource;

        internal VideoRendererPin(IBaseFilter filter)
            : base(filter)
        {
        }

        internal void SetMediaStreamSource(DirectShowMediaStreamSource mediaStreamSource)
        {
            this.mediaStreamSource = mediaStreamSource;
        }

        public override System.Collections.Generic.IEnumerable<AMMediaType> MediaTypes
        {
            get { return _mediaTypes; }
        }

        public override string Name
        {
            get { return "Video Input Pin"; }
        }

        public override bool ReceiveCanBlock
        {
            get { return true; }
        }

        protected override AllocatorProperties GetAllocatorRequirements()
        {
            return new AllocatorProperties { BuffersCount = 8, BufferSize = 100000 };
        }

        protected override void EndOfStream()
        {
            mediaStreamSource.EndOfStream();
        }

        protected override bool QueryAccept(AMMediaType mediaType)
        {
            // TODO: now only ARGB
            return (this._mediaTypes[0].MajorType.Equals(mediaType.MajorType)
                && (mediaType.SubType.Equals(MediaSubTypes.ARGB) || mediaType.SubType.Equals(MediaSubTypes.RGB24)));
        }

        protected override void Receive(IMediaSample sample)
        {
            mediaStreamSource.ReceiveMediaSample(sample);

            // Ask for new samples
            if (this.IsPullMode)
                this.RequestNextSample(sample);
        }

        public override void Inactive()
        {
            base.Inactive();

            mediaStreamSource.Stop();
        }
    }
}
